import Guide from '@/components/Guide';
import { ArrayHas, getEvenCount, getHistory, getHistoryStr, getOddAndEven, trim } from '@/utils/format';
import type { FormInstance } from 'antd/es/form';
import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Form, Input } from 'antd';
import { useEffect, useRef, useState } from 'react';
import {
  sampleSize, //获得随机数
  uniq, //去重
  take, //从0开始获得指定数组
  takeRight,
  countBy,
  slice//裁剪数组
} from "lodash"

import getChooseList from '../Home/getChooseList';
import { getFilterResult } from '../Home/getFilterResult';
import HistoryList from '@/components/Guide/HistoryList';
import IndexLocation from '@/components/Guide/IndexLocation';


export default () => {
  
  const [data, setData] = useState({
    historyListTop20:[],//最近的20期
    result:[],//所有可能的结果
    nearByList: [],//去掉上一期上下浮动20万条数据
    continue4:[],//4连号
    continue3:[],//3连号
    oneMore456:[],//1区大于4 5 6个数
    twoMore456:[],//2区大于4 5 6个数
    threeMore456:[],//3区大于4 5 6个数
    evenCount6: [],//偶数6
    evenCount5: [],//偶数5
    oddCount6: [],//奇数6
    oddCount5: [],//奇数5
    drop1112And2223: [],//去掉对称数（比如01&02和32&33）
    dropTopOddAndEevn: [],//去掉最近20期的奇偶
    filterResult:[],//过滤后的号码
  });//所有结果
  const [buyResult, setBuyResult] = useState([]);//随机出来的要买的结果
  const [lastNum, setLastNum] = useState<[]>([]);//随机出来的要买的结果
  const [chooseList , setChooseList] = useState([]);//最终筛选的需要购买的列表
  const [gaopinOddQishu, setGaopinOddQishu] = useState({});//每期奇偶组合出现的高频次数统计
  const [autoTest, setAutoTest] = useState<{}>({});//自动测试结果
  
  let caiZhongList = countBy(autoTest.result);
  
  let {
    allRedBallList,
    allRedBallStrList,
    historyList,
    historyResultStrList,
    historyOddEvenList,
    historyOddEvetTongj
  } = useModel("ballModel")

  let {
    cishuListArr,
    cishuListObj,
    cishuArr,
    sortListObj//奇偶组合距离上次出现的期数距离作为key，出现多少次作为值
  } = historyOddEvetTongj;

  useEffect(()=>{
    let filterResult = getFilterResult({
      allRedBallList: allRedBallList,
      allRedBallStrList: allRedBallStrList,
      historyList: historyList,
      historyResultStrList: historyResultStrList,
      historyOddEvenList: historyOddEvenList
    });
    setData(filterResult);

  },[]);

  let formRef = useRef<FormInstance<any>>();

  return (
    <PageContainer ghost>
     <p>开奖后，结果未更新前，测试选中概率</p>
      <table cellPadding={0}>
        <thead>
          <tr>
              <td>号码</td>
              <td>奇偶情况</td>
              <td>奇偶距上一次出现期数</td>
              <td>出现索引区间</td>
          </tr>
        </thead>
        <tbody>
          {
            buyResult.map((item, index)=>{
              let itemStr = item.join("");
              let currentOddEven = getOddAndEven(item);
              let currentJiange = historyOddEvenList.indexOf(currentOddEven);
              let locationIndex = allRedBallStrList.indexOf(itemStr);
              
              return <tr key={index} className="chooseTr" data-currentoddeven={currentOddEven}>
                <td>{item}</td>
                <td>{currentOddEven}</td>
                <td>
                  {currentJiange + 1}
                  （间隔出现过{sortListObj[currentJiange + 1]}次）
                  <p>
                    猜中 {
                      getZhongjiangNum(lastNum, item)
                    } 个
                  </p>
                </td>
                <td>
                  <IndexLocation locationIndex={locationIndex}></IndexLocation>
                </td>
              </tr>
            })
          }
          <tr>
            <td colSpan={5}>随机选择：随机产生总结果：{chooseList.length}个</td>
          </tr>
        </tbody>
      </table>
      <div>
        筛选规则：
      </div>
      <Form
        ref={formRef} 
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        style={{
          maxWidth: 600,
        }}
        initialValues={{
          remember: true,
        }}
        autoComplete="off"
        onFinish={(values)=>{
          console.log('data.filterResult', data.filterResult.length);
          
          let sourceList = getChooseList({
            filterList: data.filterResult,
            values: values
          });
          setChooseList(sourceList);//最终筛选的以红1开头的所有结果
          setLastNum(values.lastResult.split(" "));//开奖结果，用来验证一下上一期的中奖率，最后一期数据没更新时可以填
          let result = sampleSize(sourceList, 10);//随机10条结果备选
          setBuyResult(result);
        }}
      >
        <Form.Item
          label="开头数值"
          name="startNum"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="最近一期开奖结果"
          name="lastResult"
        >
          <Input />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit" className=' mr-3'>
            生成
          </Button>
          <Button type="primary" onClick={()=>{
            let sourceList = getChooseList({
              filterList: data.filterResult,
              values: formRef.current?.getFieldsValue()
            });
            let {lastResult} = formRef.current?.getFieldsValue();
            console.log(sourceList);
            let testResult:any[] = [];//记录中奖次数
            let testTime = 0;//记录计算的次数
            let interVal = setInterval(()=>{
              let result = sampleSize(sourceList, 10);//随机10条结果备选
              result.find((item:any)=>{
                let count = getZhongjiangNum(lastResult, item);
                testResult.push(count);
                testTime++;//计算一次，次数+1
                if(count == 6 || testTime >= 10000){//如果中了6红 || 计算了100次
                  clearInterval(interVal);//终止循环
                  setAutoTest({
                    result: testResult,
                    testTime: testTime
                  });
                  return true;
                }
              });
            }, 10)
          }}>
            自动测试
          </Button>
        </Form.Item>
      </Form>
      {
        autoTest?.result?.length > 0
        &&<>
          <p>测试结果：</p>
          <p>测试了 {autoTest.testTime} 次</p>
          <div>
            {Object.keys(caiZhongList).map((key, index)=>{
              let jilv = caiZhongList[key]/autoTest.result.length*100;
              jilv = jilv.toFixed(2);
              return <p key={index}>
                猜中 {key} 个球：{caiZhongList[key]}次，几率 {jilv} %
              </p>
            })}
          </div>
          <p>第一次猜中4球次数：{autoTest.result.indexOf(4) + 1}</p>
          <p>第一次猜中5球次数：{autoTest.result.indexOf(5) + 1}</p>
          <p>第一次猜中6球次数：{autoTest.result.indexOf(6) + 1}</p>
          <p>猜中情况为：{autoTest.result.join("，")}</p>
        </>
      }
    </PageContainer>
  );
};

function getZhongjiangNum(lastNum:[], chooseNum:[]){
  let count = 0;
  chooseNum.forEach((item)=>{
    if(lastNum.indexOf(item)>-1){
      count++
    }
  });
  return count;
}